import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:largefriends/pages/lf_test/lf_test_view.dart';
import 'package:largefriends/widgets/lf_horizontal_scroll/lf_horizontal_scroll_item.dart';

class LfHorizontalScrollWidget extends StatefulWidget {
  const LfHorizontalScrollWidget(
      {super.key, required this.list, this.onTap, required this.selectedValue});
  final int selectedValue;
  final List<TestDataType> list;
  final Function(int value)? onTap;
  @override
  State<LfHorizontalScrollWidget> createState() =>
      _LfHorizontalScrollWidgetState();
}

class _LfHorizontalScrollWidgetState extends State<LfHorizontalScrollWidget> {
  ScrollController controller = ScrollController();
  RxDouble scrollOffset = 0.0.obs;
  RxDouble max = 0.0.obs;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      if (mounted) {
        if (controller.hasClients) {
          max.value = controller.position.maxScrollExtent;
        }
      }
    });

    controller.addListener(() {
      scrollOffset.value = controller.offset;
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      child: SizedBox(
        // height: 300,
        child: ScrollConfiguration(
          behavior: const ScrollBehavior(),
          child: SingleChildScrollView(
            controller: controller,
            scrollDirection: Axis.horizontal,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: List.generate((widget.list.length / 3).ceil(), (index) {
                return Obx(() => LfHorizontalScrollItem(
                    max: max,
                    scrollOffset: scrollOffset,
                    selectedValue: widget.selectedValue,
                    onTap: widget.onTap,
                    list: widget.list.sublist(index * 3,
                        math.min(index * 3 + 3, widget.list.length))));
              }),
            ),
          ),
        ),
      ),
    );
  }
}
